<?php


namespace Modules\Cms\Http\Controllers\Web;
use Intervention\Image\ImageManagerStatic as Image;
use Endroid\QrCode\QrCode;
use Endroid\QrCode\Writer\PngWriter;
use App\Helpers\ViewHelpers;
use App\Http\Controllers\MyController;
use Modules\Cms\Http\Requests\ArticleCommentRequest;
use Modules\Cms\Models\Article;
use Modules\Cms\Models\ArticleCategory;
use Modules\Cms\Models\ArticleComment;
use Modules\Cms\Models\ArticleTag;
use Addons\Ads\Models\Ads;
use Illuminate\Http\Request;
use App\Models\UserInfo;
use Illuminate\Support\Facades\Auth;
use Illuminate\Http\Response;
use Modules\Cms\Models\ArticleAds;
use Modules\User\Models\User;
use Modules\Cms\Models\ArticleMeta;

class CmsController extends MyController
{

    use ViewHelpers;

    public function index(Request $MyRequest)
    {
        session([
            'the_page' => 'user',
            'page_title' => "首页",
        ]);
        $id = $MyRequest->get('cid', 0);
        $list=Ads::where('code','home')->orderBy('id','desc')->get();
        foreach ($list as $k=>$v){
            $json=json_decode($v->content,true);
            $v->url=$json[0]['url'];
            $v->img=$json[0]['path'];
        }
        if($id){
          $Articlelist=Article::where('category_id',$id)->where('status',1)->orderBy('id','desc')->get();  
        }else{
            $Articlelist=Article::where('status',1)->orderBy('view','desc')->get();
        }
        $clist=ArticleCategory::orderBy('id','asc')->get();
        return $this->theme('index',['list'=>$list,'article_list'=>$Articlelist,'clist'=>$clist,'id'=>$id]);
    }
   
    public function honor(Request $request)
    {
        $type=$request->get('have');
        $uid=Auth::check()?auth()->user()->id:0;
       session([
            'the_page' => 'honor',
            'page_title' => "荣誉",
        ]);
        if($type=='join'){
            $list=ArticleComment::with('article')->where('user_id',$uid)->get();
        }elseif($type=='done'){
             $date=time();
             $alist=Article::where('status',1)->orderBy('id','desc')->get();
             $list=[];
             foreach ($alist as $k=>$v){
                 $x=!empty(explode(' - ',$v->author))?strtotime(explode(' - ',$v->author)[1]):$date;
                 if($x<$date){
                        $v->iscomment=ArticleComment::where('user_id',$uid)->where('single_id',$v->id)->first()?1:0;
                        $list[]=$v;  
                 }
             }
        }else{
            $list=[];
            $alist=Article::where('status',1)->orderBy('id','desc')->get();
            foreach ($alist as $k=>$v){
                if(!ArticleComment::where('user_id',$uid)->where('single_id',$v->id)->first()){
                    $list[]=$v;  
                }
            }
        }
        return $this->theme('honor',['list'=>$list,'have'=>$type]);   
    }
    public function share(Request $request)
    {
        $id=$request->get('id');
        $uid=Auth::check()?auth()->user()->id:0;
        session([
            'the_page' => 'cms.share',
            'page_title' => "邀请好友",
        ]);
        $list=ArticleAds::where('single_id',$id)->orderBy('id','desc')->get();
     
        return $this->theme('share',['list'=>$list,'uid'=>$uid,'id'=>$id]);
    }
 
    public function category($id)
    {
        $category = ArticleCategory::find($id);

        if (empty($category)) {
            abort(404);
        }

        is_category($category);

        return $this->theme($this->cmsCategoryTemplate($category), compact('category'));
    }

    public function single(Request $request,$id)
    {
        $article = article($id);
        $tuid=$request->get('from',0);

        if (empty($article)) {
            abort(404);
        }

        is_single($article);

        $config = system_config([], 'cms');
        
        $islogin=Auth::check()?auth()->user()->id:0;
        $iscomment=0;
        $isinfo=0;
        if($islogin){
          $iscomment=ArticleComment::where('user_id',$islogin)->where('single_id',$id)->first()?1:0;
          $isinfo=UserInfo::where('user_id',$islogin)->first()?1:0;
        }

        return $this->theme($this->cmsArticleTemplate($article), compact('article','tuid', 'config','islogin','iscomment','isinfo','id'));
    }


    public function tag($id)
    {
        $tag = ArticleTag::find($id);

        if (empty($tag)) {
            abort(404);
        }

        is_tag($tag);

        return $this->theme('tag', compact('tag'));
    }

    public function search($keyword)
    {
        $keyword = $this->filter($keyword, '');

        if (empty($keyword)) {
            abort(404);
        }

        is_search($keyword);

        return $this->theme('search', compact('keyword'));
    }
   public function comment(Request $request)
    {
       $id=$request->get('id');
       $tuid=$request->get('tuid');
       $uid=Auth::check()?auth()->user()->id:0;
       if(!ArticleComment::where('user_id',$uid)->where('single_id',$id)->first()){
            $info=UserInfo::where('user_id',$uid)->first();
            $comment = [
                'single_id' => $id,
                'tuid'=>$tuid,
                'user_id' => auth()->user()->id,
                'root_id' => $info->id,
                'parent_id' => 0,
                'status' => isset($config['is_auto_status']) && $config['is_auto_status'] == 1 ? 1 : 0,
                'content' => '',
            ];
            $result = (new ArticleComment())->store($comment);
            //报名成功 给积分
            $point=ArticleMeta::where('article_id',$id)->where('meta_key','share_point')->value('meta_value')?:0;
            if($point&&User::where('id',$tuid)->first()){
                $pointRes = app('user')->point($point, $tuid, $id,2,'邀请用户报名+'.$point); 
            }
            return $this->result(true, ['msg' => "报名成功!"]); 
       }
        return $this->result(false, ['msg' => "已报名了!"]); 
    } 
    
    public function createComment(ArticleCommentRequest $request)
    {
        $config = system_config([], 'cms');

        if (isset($config['is_allow_comment']) && $config['is_allow_comment'] == 1) {

            $data = $request->validated();
            $content = strip_tags(paramFilter($data['content']));

            $article = article($data['single_id']);

            if (!$article) {
                return $this->result(false, ['msg' => '非法参数.']);
            }

            $pid = $data['parent_id'];
            $rid = 0;

            if ($pid > 0) {

                $obj = comment($pid, $data['single_id']);

                if (!$obj) {
                    return $this->result(false, ['msg' => '非法参数.']);
                }

                $rid = $obj->parent_id == 0 ? $obj->id : $obj->root_id;
            }

            $comment = [
                'single_id' => $data['single_id'],
                'user_id' => auth()->user()->id,
                'root_id' => $rid,
                'parent_id' => $pid,
                'status' => isset($config['is_auto_status']) && $config['is_auto_status'] == 1 ? 1 : 0,
                'content' => $content,
            ];

            $result = (new ArticleComment())->store($comment);
            return $this->result($result);
        }

        return $this->result(false);

    }
}
